﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using Summer.Model.Common;
using Autofac;
using Autofac.Extensions.DependencyInjection;
using System.Reflection;

namespace Summer.WebApi
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public IServiceProvider ConfigureServices(IServiceCollection services)//IServiceProvider
        {
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
            //注入Swagger
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Swashbuckle.AspNetCore.Swagger.Info
                {
                    Title = "swagger xml api demo",
                    Version = "v1",
                });

                var xmlPath = System.IO.Path.Combine(AppContext.BaseDirectory, "Swagger.xml");
                c.IncludeXmlComments(xmlPath);
            });

            services.Configure<IConfiguration>(Configuration);

            services.Configure<DBOptions>(Configuration.GetSection("DBOptions"));

            //services.Add(new ServiceDescriptor(typeof(IService.IDBFactory), typeof(Service.DBFactory), ServiceLifetime.Scoped));
            //services.AddScoped<IService.IDBFactory, Service.DBFactory>();
            //services.AddScoped<IService.v1.IusersService, Service.v1.usersService>();

            //注入JWT
            //services.Configure<JwtSettings>(Configuration.GetSection("JwtSettings"));
            JwtSettings settings = new JwtSettings();
            Configuration.Bind("JwtSettings", settings);
            services.AddAuthentication(option =>
            {
                option.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                option.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(config =>
            {
                config.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidAudience = settings.Audience,
                    ValidIssuer = settings.Issuer,
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(settings.SecretKey))
                };
            });


            #region autofac

            //实例化 AutoFac  容器   
            var builder = new ContainerBuilder();

            //要记得!!!这个注入的是实现类层，不是接口层！不是 IServices
            var assemblysServices = Assembly.Load("Summer.Service");
            //指定已扫描程序集中的类型注册为提供所有其实现的接口。
            builder.RegisterAssemblyTypes(assemblysServices).AsImplementedInterfaces()
                .InstancePerLifetimeScope();//.AsSelf()

            //builder.RegisterType<Service.v1.usersService>();
            //builder.RegisterType<Service.DBFactory>();

            //将services填充到Autofac容器生成器中
            builder.Populate(services);
            //使用已进行的组件登记创建新容器
            var Container = builder.Build();

            #endregion

            return new AutofacServiceProvider(Container);

        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            app.UseSwagger();

            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "swagger xml api demo");
            });
            app.UseAuthentication();

            app.UseMvc();
        }
    }
}
